/* eslint-disable max-lines */
import TauActionPanel from '@/components/TauActionPanel';
import TauPage from '@/components/TauPage';
import TauTable from '@/components/TauTable';
import MoreFuncDropDown from '@/components/MoreFuncDropDown';
import { useStore } from '@/hooks';
import { Button, Dialog, Drawer, Loading, Message, Tab } from '@alifd/next';
import { t } from '@lingui/macro';
import { uniqueId } from 'lodash';
import { observer } from 'mobx-react-lite';
import React, { useEffect, useRef, useState } from 'react';
import { ENUMS, MAGIC_NUMBERS, column, toSelectDataSource } from './stores/definitions';
import AddForm from './components/AddForm';
import DetailDrawer from './components/DetailDrawer';
import OrderRefund from './components/refund/OrderRefund';
import ChangeOrderDrawer from './components/ChangeOrderDrawer';
import { toJS } from 'mobx';
import moment from 'moment';
import { areArraysEqual, arrayContrast } from './stores/method';
import ComponentsDrawer from '@/components/Drawers/ComponentsDrawer';
import useDebounce from '@/hooks/useDebounce';
import SupplementPay from './components/SupplementPay';

const tableId = uniqueId('tauTable-');

const tabItems = [
  { key: '0', label: t`包车订单` },
  { key: '1', label: t`退款记录` },
];

function parseRegion(s) {
  if (!s?.length) return {};
  return { main: s[0]?.itemId, minor: s[1]?.itemId };
}


function CcOrder({ filter, hideActions, hiddenSearchItems = [], queryParams }) {
  const [modal, setModal] = useState([]);
  const { ccOrderStore: store } = useStore();
  const orderRef = useRef();
  const changedRef = useRef();

  useEffect(() => {
    if (queryParams) {
      store._mainArgs.isView = true;
    }
    store._mainArgs.search = {
      ...queryParams,
      ...store._mainArgs.search,
      ...filter,
    };
    return () => {
      store.tabKey = '0';
      store._mainArgs.dataSource = [];
      store._mainArgs.isView = false;
    };
  }, []);

  // 获取列表数据
  const handleOnSearch = (params) => {
    const { orderDate, getOnDate, orderStatus, startRegion: __, endRegion: ___, ...searchArgs } = params.values;
    const { startRegion, endRegion } = params.valueObjects;
    const [from, to] = orderDate || [];
    const [fromTime, toTime] = getOnDate || [];
    const { main: startMainArea, minor: startMinorArea } = parseRegion(startRegion?.selectedPath);
    const { main: endMainArea, minor: endMinorArea } = parseRegion(endRegion?.selectedPath);

    let statusParam = {};

    if (queryParams) {
      statusParam = { success: [orderStatus] };
    } else {
      statusParam = { orderStatus };
    }

    store._mainArgs.search = {
      ...filter,
      ...queryParams,
      from,
      to,
      fromTime,
      toTime,
      startMainArea,
      startMinorArea,
      endMainArea,
      endMinorArea,
      ...searchArgs,
      ...statusParam,
    };
  };

  /**
   * @desc
   * @param {}
   * @return {}
   */
  const handleTableAction = (info, action) => {
    switch (action) {
      case 'viewOrder':
        handleOpenOrder(info);
        break;
      case 'changeOrder':
        handleOpenChangeOrder(info);
        break;
      case 'applyRefund':
        handleOrderRefund(info);
        break;
      case 'customerForm':
        handleOpenCustomer(info);
        break;
      default:
        break;
    }
  };

  const handleOpenCustomer = (order) => {
    orderRef.current = order;
    setModal(['customerForm']);
  };

  // 点击打开查看
  const handleOpenOrder = (order) => {
    orderRef.current = order;
    changedRef.current = undefined;
    setModal(['view']);
  };


  // 点击发起取消及退款
  const handleOrderRefund = (order) => {
    orderRef.current = order;
    changedRef.current = undefined;
    setModal(['refund']);
  };

  // 点击进入人工变更
  const handleOpenChangeOrder = (order) => {
    orderRef.current = order;
    setModal(['orderChange']);
  };

  // Modal窗口关闭回调
  const handleCancel = () => {
    if (!_.isEmpty(changedRef.current)) {
      Dialog.confirm({
        content: t`放弃修改内容？`,
        onOk: () => setModal([]),
      });
      return;
    }
    setModal([]);
  };

  const handleCancelOrder = (result) => {
    Dialog.confirm({
      content: t`是否取消订单？`,
      onOk: async () => {
        try {
          const { id } = toJS(result);
          await store.orderCancel({ orderId: id });
          Message.success({ content: t`成功取消订单` });
        } catch (error) {
          Message.error({ content: t`取消订单失败`, duration: 5000 });
          throw error;
        }
      },
    });
  };

  const handleOrderEnableShare = (result) => {
    Dialog.confirm({
      content: t`是否开启分账？`,
      onOk: async () => {
        try {
          const { id } = toJS(result);
          await store.orderEnableShare({ orderId: id });
          Message.success({ content: t`成功开启分账` });
        } catch (error) {
          Message.error({ content: t`开启分账失败`, duration: 5000 });
          throw error;
        }
      },
    });
  };

  // 变更数据提交
  const handleUpdate = async (result) => {
    if (!_.isEmpty(changedRef.current)) {
      try {
        await store.update(result);
        Message.success({ content: t`修政成功` });
      } catch (e) {
        Message.error({ content: t`修政失败`, duration: 7000 });
        throw e;
      }
    }
    setModal([]);
  };

  /**
   * 发起申请退款
   * @param {*} result 数据
   * @param {*} state
   * @param {*} type
   */
  const handleRefund = useDebounce(async (result, state, type, A, B, isAB, open, account, accountSp) => {
    if (!_.isEmpty(result)) {
      try {
        const { id, distanceTime, cancelTime, refundPrice,
          cancelRemark = '', attachments = [], price, ccOrder,
          serviceCharge, cancelOrder, cancelCoupon, cancelCouponB, enableProfitShare, refundPriceB,
          cancelRemarkB, priceB, distanceTimeB, cancelTimeB } = toJS(result);
        const utcTime = moment.utc(cancelTime).subtract('8', 'hours').toISOString();
        const utcTimeB = moment.utc(cancelTimeB).subtract('8', 'hours').toISOString();
        let data;
        let args = {};
        const equalA = areArraysEqual(account, A);
        const computeAccountA = arrayContrast(open, account, A);
        if (store._orderRefundStatus === '0') {
          if (isAB) {
            const equalB = areArraysEqual(store.accountB, B);
            const computeAccountB = arrayContrast(open, store.accountB, B);
            data = [
              {
                distanceTime,
                cancelTime: utcTime,
                refundPrice: Number(refundPrice),
                cancelRemark,
                type,
                state,
                orderPrice: price,
                orderState: ccOrder.orderStatus,
                attachments,
                serviceCharge,
                cancelCoupon,
                orderInfo: {
                  directRoute: false,
                  orderId: id,
                  suborderId: `${id}-1`,
                },
              },
              {
                distanceTime: distanceTimeB,
                cancelTime: utcTimeB,
                refundPrice: Number(refundPriceB),
                cancelRemark: cancelRemarkB,
                type,
                state,
                orderPrice: priceB,
                orderState: ccOrder.orderStatus,
                attachments,
                serviceCharge,
                cancelCouponB,
                refundPayers: computeAccountB,
                orderInfo: {
                  directRoute: true,
                  orderId: id,
                  suborderId: `${id}-2`,
                },
              }];
            if (!equalA) {
              data[0].refundPayers = computeAccountA;
            }
            if (!equalB) {
              data[1].refundPayers = computeAccountB;
            }
          } else {
            data = [
              {
                distanceTime,
                cancelTime: utcTime,
                refundPrice: Number(refundPrice),
                cancelRemark,
                type,
                state,
                orderPrice: price,
                orderState: ccOrder.orderStatus,
                attachments,
                serviceCharge,
                orderInfo: {
                  directRoute: false,
                  orderId: id,
                  suborderId: `${id}-1`,
                },
                cancelCoupon,
              }];
            if (!equalA) {
              data[0].refundPayers = computeAccountA;
            }
          }
          args = {
            cancelOrder,
            enableProfitShare,
            report: true,
          };
        } else if (isAB) {
          // 追加退款 区分ab段
          data = [{
            outTradeNo: id, // 订单id
            subOutTradeNo: `${id}-1`,
            amount: parseFloat(refundPrice) * 100,
            reason: cancelRemark,
            attachments: attachments || [],
            payType: '3', // 业务类型 约定给3
          }, {
            outTradeNo: id, // 订单id
            subOutTradeNo: `${id}-2`,
            amount: parseFloat(refundPriceB) * 100,
            reason: cancelRemarkB,
            attachments: attachments || [],
            payType: '3', // 业务类型 约定给3
          }];
        } else {
          const _account = _.cloneDeep(accountSp);
          const distributeInfos = [];
          for (let i = 0; i < _account.length; i++) {
            const { check, contributionAmount = 0, targetId, targetName, targetType } = _account[i];
            if (check) {
              distributeInfos.push({
                amount: contributionAmount * 100,
                targetId,
                targetName,
                targetType,
              });
            }
          }
          _.assign(args, {
            orderId: id,
            reason: cancelRemark,
            attachments: attachments || [],
            distributeInfos,
          });
        }
        if (store._orderRefundStatus === '0') {
          await store.orderSponsorRefund(id, data, args);
        } else {
          await store.orderCreateOffline(args);
        }
        Message.success({ content: t`申请退款成功` });
      } catch (e) {
        Message.error({ content: t`申请退款失败`, duration: 7000 });
        throw e;
      }
    }
    setModal([]);
  }, 200);

  const handleOnChangeTab = (v) => {
    store._mainArgs.dataSource = [];
    store.tabKey = v;
    store._mainArgs.query({ page: 0 });
  };

  const handleSupplementPay = (result) => {
    orderRef.current = result;
    setModal(['supplement']);
  };

  const handleSupplementSubmit = async (result) => {
    if (!_.isEmpty(result)) {
      try {
        const _result = toJS(result);
        await store.offlineAddPay(_result);
        Message.success({ content: t`追加支付成功` });
      } catch (error) {
        Message.error({ content: t`追加支付失败：${error?.source?.message}`, duration: 7000 });
        throw error;
      }
    }
    setModal([]);
  };

  return (
    <TauPage className="page-container">
      <TauActionPanel
        onSearch={handleOnSearch}
        actions={hideActions ? [] : [
          {
            name: 'btn-placeOrder',
            title: t`人工下单`,
            type: 'primary',
            onClick: () => setModal(['placeOrder']),
          },
        ]}
        searchItems={store._tabKey === '1' ?
          [
            {
              name: 'orderDate',
              type: 'date-range',
              props: {
                placeholder: [t`退款起始时间`, t`退款结束时间`],
              },
            },
            {
              name: 'state',
              type: 'select',
              props: {
                dataSource: toSelectDataSource(ENUMS.state),
                placeholder: t`申请状态`,
              },
            },
            {
              name: 'type',
              type: 'select',
              props: {
                dataSource: toSelectDataSource(ENUMS.refundType),
                placeholder: t`退款类型`,
              },
            },
          ]
          : [
            { // 字典tree级联选择
              name: 'startRegion',
              type: 'dict-tree',
              props: { placeholder: t`始发区域`, changeOnSelect: true, dictId: 'region', maxLevel: 2, style: { minWidth: '160px' } },
            },
            {
              name: 'endRegion',
              type: 'dict-tree',
              props: { placeholder: t`结束区域`, changeOnSelect: true, dictId: 'region', maxLevel: 2, style: { minWidth: '160px' } },
            },
            {
              name: 'orderDate',
              type: 'date-range',
              props: {
                placeholder: [t`起始订单时间`, t`结束订单时间`],
              },
            },
            {
              name: 'getOnDate',
              type: 'date-range',
              props: {
                placeholder: [t`起始上车时间`, t`结束上车时间`],
              },
            },
            { // 字典项下拉列表
              name: 'portType',
              type: 'dict-item',
              props: { placeholder: t`口岸`, dictId: 'port' },
            },
            { // 字典项下拉列表
              name: 'vehicleType',
              type: 'dict-item',
              props: { placeholder: t`车型`, dictId: 'vehicle' },
            },
            { // 字典项下拉列表
              name: 'orderOptionType',
              type: 'dict-item',
              props: { placeholder: t`订单选项类型`, dictId: 'orderOption' },
            },
            { // 字典项下拉列表
              name: 'orderType',
              type: 'dict-item',
              props: { placeholder: t`订单类型`, dictId: 'orderType' },
            },
            { // 字典项下拉列表
              name: 'orderStatus',
              type: 'dict-item',
              props: { placeholder: t`订单状态`, dataSource: toSelectDataSource(ENUMS.orderStatus) },
            },
            {
              name: 'refundStatus',
              type: 'select',
              props: {
                dataSource: toSelectDataSource(ENUMS.refundStatus),
                placeholder: t`退款状态`,
              },
            },
          ].filter((si) => hiddenSearchItems.indexOf(si.name) === -1)}
        keywordSearch={{
          // enabled: true,
          placeholder: t`请输入关键字搜搜`,
        }}
        className="action-panel"
      />
      <div className="content">
        <Loading visible={store._mainArgs.loading}>
          <Tab
            accessKey={store.tabKey}
            onChange={(v) => handleOnChangeTab(v)}
          >
            {tabItems.map((item) => (<Tab.Item key={item.key} title={item.label} />))}
          </Tab>
        </Loading>
        {store._tabKey === '1' ?
          <TauTable
            instanceId={tableId}
            primaryKey="refundNumber"
            tableLayout="fixed"
            currentPage={store._mainArgs.pg.page}
            pageSize={store._mainArgs.pg.size}
            total={store._mainArgs.total}
            sort={store._mainArgs.tableSort}
            onFetch={(pg) => { store._mainArgs.pg = pg; }}
            loading={store._mainArgs.loading}
            expandedRowIndent={[300, 100]}
            dataSource={toJS(store._mainArgs.dataSource)}
            columns={[
              { title: t`编号`, dataIndex: 'idx', width: 44, cell: (v, i) => store._mainArgs.idx(i) },
              column('orderInfo.orderId', {
                width: 200,
                cell: (v, _, row) => {
                  return (
                    <Button
                      key={row.id}
                      type="primary"
                      text
                      onClick={() => handleTableAction(row, 'viewOrder')}
                    >
                      {v}
                    </Button>
                  );
                },
              }),
              column('applicationId', { width: 180 }),
              column('orderInfo.name', { width: 98 }),
              column('type', { width: 138 }),
              column('state', { width: 118 }),
              column('cancelTime', { width: 180 }),
              column('refundTime', { width: 180 }),
              column('refundPrice', { width: 118 }),
              column('cancelRemark', { width: 200 }),
            ].filter((c) => c.dataIndex !== 'action' || !hideActions)}
          /> :
          <TauTable
            instanceId={tableId}
            primaryKey="orderNumber"
            tableLayout="fixed"
            currentPage={store._mainArgs.pg.page}
            pageSize={store._mainArgs.pg.size}
            total={store._mainArgs.total}
            sort={store._mainArgs.tableSort}
            onFetch={(pg) => { store._mainArgs.pg = pg; }}
            loading={store._mainArgs.loading}
            dataSource={toJS(store._mainArgs.dataSource)}
            columns={[
              { title: t`序号`, dataIndex: 'idx', width: 44, cell: (v, i) => store._mainArgs.idx(i) },
              {
                title: t`订单号`,
                width: 200,
                cell: (v, _, row) => {
                  return (
                    <Button
                      key={row.id}
                      type="primary"
                      text
                      onClick={() => handleTableAction(row, 'viewOrder')}
                    >
                      {row.id}
                    </Button>
                  );
                },
              },
              column('ccOrder.orderType', { width: 58 }),
              column('ccOrder.routeText', { width: 110 }),
              column('ccOrder.subscribeName', {
                width: 58,
                cell: (v, i, r) => <Button type="primary" text onClick={() => handleTableAction(r, 'customerForm')}>{v}</Button>,
              }),
              column('company.name', { width: 78 }),
              column('price', { width: 78 }),
              column('ccOrder.orderStatus', { width: 58 }),
              column('sourceGroup', { width: 200 }),
              column('crDate', { width: 124, sortable: true }),
              column('ccOrder.predictBeginDate', { width: 124, sortable: true }),
              {
                title: t`操作`,
                dataIndex: 'action',
                width: 138,
                cell: (_, __, order) => {
                  const { ORDER_STATE } = MAGIC_NUMBERS;
                  const { enableProfitShare = false, ccOrder } = order || {};
                  const { orderStatus } = ccOrder;
                  const funcMenu = [
                    {
                      title: t`退款`,
                      onClick: () => handleTableAction(order, 'applyRefund'),
                    },
                    // {
                    //   title: '取消',
                    //   onClick: () => handleTableAction(order, 'cancelOrder'),
                    //   show: [ORDER_STATE.PAID, ORDER_STATE.START].includes(orderStatus),
                    // },
                    {
                      title: t`订单变更`,
                      onClick: () => handleTableAction(order, 'changeOrder'),
                      show: [ORDER_STATE.PAID, ORDER_STATE.START, ORDER_STATE.FINISH].includes(orderStatus),
                    },
                    {
                      title: t`取消订单`,
                      onClick: () => handleCancelOrder(order),
                      show: [ORDER_STATE.PAID, ORDER_STATE.START].includes(orderStatus),
                    },
                    {
                      title: t`开启分账`,
                      onClick: () => handleOrderEnableShare(order),
                      show: !enableProfitShare,
                    },
                    {
                      title: t`追加支付`,
                      onClick: () => handleSupplementPay(order),
                    },
                  ];
                  return (
                    <MoreFuncDropDown
                      dropdownItems={funcMenu}
                      maxShow={1}
                    />
                  );
                },
              },
            ].filter((c) => c.dataIndex !== 'action' || !hideActions)}
          />
        }
      </div>
      <Drawer
        visible={modal[0] === 'placeOrder'}
        title={t`人工下单`}
        onClose={() => setModal([...modal, `toClose$${Date.now()}`])}
        closeMode={['esc', 'mask', 'close']}
        style={{ maxWidth: '90%' }}
        width="90%"
      >
        <AddForm
          modal={modal}
          onCancel={handleCancel}
          onSubmit={() => { }}
        />
      </Drawer>
      <Drawer
        visible={modal[0] === 'refund'}
        title={t`申请退款`}
        onClose={() => setModal([...modal, `toClose$${Date.now()}`])}
        closeMode={['esc', 'mask', 'close']}
        style={{ maxWidth: '70%' }}
        width="90%"
      >
        <OrderRefund
          modal={modal}
          order={orderRef.current}
          onCancel={handleCancel}
          onSubmit={handleRefund}
        />
      </Drawer>
      <Drawer
        visible={modal[0] === 'supplement'}
        title={t`追加支付`}
        onClose={() => setModal([...modal, `toClose$${Date.now()}`])}
        closeMode={['esc', 'mask', 'close']}
        style={{ maxWidth: '70%' }}
        width="90%"
      >
        <SupplementPay
          modal={modal}
          order={orderRef.current}
          onCancel={handleCancel}
          onSubmit={handleSupplementSubmit}
        />
      </Drawer>
      <DetailDrawer
        modal={modal}
        handleUpdate={handleUpdate}
        visible={modal[0] === 'view' || modal[0] === 'edit'}
        orderId={orderRef.current?.orderNumber || orderRef.current?.orderInfo?.orderId}
        onClose={() => {
          setModal([]);
        }}
      />
      <ChangeOrderDrawer
        visible={modal[0] === 'orderChange'}
        order={orderRef.current}
        onClose={async (flushed) => {
          setModal([]);
          if (flushed) {
            await store._mainArgs.query();
          }
        }}
      />
      {/* <CancelOrderDialog
        visible={modal[0] === 'cancelOrder'}
        orderId={orderRef.current?.id}
        onClose={() => {
          setModal([]);
        }}
      /> */}
      <ComponentsDrawer modal={modal} queryParams={{ username: orderRef.current?.username }} name={orderRef.current?.ccOrder?.subscribeName} onCancel={handleCancel} />
    </TauPage>
  );
}

export default observer(CcOrder);
